<?php

/**
 * 消费者(用户模型实体)
 * User: mr2longly <mr2longly@gmail.com>
 * Date: 6/25/16
 * Time: 15:25
 */

namespace Home\Model;


use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Log;
use Think\Model;

class CustomerModel extends Model {
    const SEARCH_TYPE_REVIEWED = 0; //审批
    const SEARCH_TYPE_MOD_LOCATION = 1; //修改本地人
    const SEARCH_TYPE_ASSURE = 2; //担保
    const SEARCH_TYPE_UPLOAD = 3; //上传资料

    public function has($data, $throwException = true) {
        if (is_numeric($data)) {
            $data = ['id' => $data];
        }

        if (!is_array($data)) {
            if ($throwException) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            return null;
        }

        $data['status'] = array('not in',"'".Constant::CUSTOMER_USE."'","'".Constant::CUSTOMER_NOUSE."'");
        $information = M('Customer')->where($data)->find();

        if (!$information) {
            $throwException && BusinessException::throwException(Constant::CUSTOMER_NOT_FOUND);
        } else {
            $information['max_amount'] = Constant::MAX_CREDIT_AMOUNT;
            $information['isset_pay_pass'] = !empty($information['pay_pass']);
            unset($information['password'], $information['pay_pass']);
        }

        return $information;
    }

    /**
     * 更新用户可用授信余额
     * @param $customerId
     * @param $amount
     * @return bool
     */
    public function updateBalance($customerId, $amount)
    {
        if (is_numeric($customerId) && is_numeric($amount)) {
            $currentBalance = $this->where(['id'=>$customerId])->getField("balance_amount");
            $balance = intval($currentBalance)+$amount;
            if ($balance<=0) {
                $balance = 0;
            }
            return $this->where(['id'=>$customerId])->setField('balance_amount', $balance);
        }
        return false;
    }

    /**************************************************************************
     * 功能描述：更新用户的设备id（老用户更换手机登陆）
     * @param $oldDeviceId
     * @param $newDeviceId
     * @return bool
     **************************************************************************/
    public function updateDeviceId($id,$newDeviceId){
        return $this->where(['id' => $id])->setField('device_id', $newDeviceId);
    }

    public function getAgeById($id){ 
            
        //过了这年的生日才算多了1周岁 
        if(empty($id)) return ''; 
        $date=strtotime(substr($id,6,8));
        //获得出生年月日的时间戳 
        $today=strtotime('today');
        //获得今日的时间戳 
        $diff=floor(($today-$date)/86400/365);
        //得到两个日期相差的大体年数 
        
        //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比 
        $age=strtotime(substr($id,6,8).' +'.$diff.'years')>$today?($diff+1):$diff; 
  
        return $age;
    }

    public function getAddressById($id){ 
            
        $url = "http://apis.juhe.cn/idcard/index?key=d39a15e97c868ab2aaaeb6bc0dc841a5&cardno=$id";
        $content = file_get_contents($url);
        $result = json_decode($content,true);
        $data = array();
        if($result){
            if($result['error_code']=='0'){
                $data =$result['result'];
            }
        }
        return $data;
    }

    /************************************************************************
     * 功能描述：查询当前用户当前机型权限禁止次数
     * 创建时间：2016-8-18
     *************************************************************************/
    public function getCountPermission($customerId, $deviceId, $permissionType)
    {
        $permission = M('customerDeviceHis')->where(['customer_id'=>$customerId, 'device_id'=>$deviceId,
            'permission_type'=>$permissionType])->count('device_id');
        return $permission;
    }

    /**
     * 校验手机号是否注册过
     */
    public function chkCustomerByMobile($mobile){
        $res = M('Customer')->where(['mobile' => $mobile])->select();
        if($res){
            if(count($res) > 1){
                $ret['count'] = count($res);
                return $ret;
            }
            $res[0]['count'] = 1;
            return $res[0];
        }

        return false;
    }

    public function getIsnotLocalCustomerList($mobile_key, $search, $county_id_str=NULL)
    {
        //搜索字段
        $key_words = " c.id, c.real_name, c.mobile, c.id_num, c.gender, c.birthplace, c.is_local ";
        /*if ($search['tool_id'] == CustomerModel::SEARCH_TYPE_ASSURE){
            $key_words = " c.real_name, c.mobile, c.gender, c.birthplace, h.amount, h.id AS consume_id,
            FROM_UNIXTIME(h.add_time, '%Y-%m-%d %H:%i:%s') AS add_time, h.type, h.status, h.repay_id ";
        }*/

        //sql拼接
        $sql = "SELECT ".$key_words." FROM customer c ";
        $where = " WHERE c.type = 1 AND c.mobile like '".$mobile_key."%' AND c.id_num != '' ";
        if ($search['tool_id'] == CustomerModel::SEARCH_TYPE_MOD_LOCATION){
            //修改本地人
            $sql .= $where;
            $sql .= ' ORDER BY id DESC LIMIT 10';
        }elseif ($search['tool_id'] == CustomerModel::SEARCH_TYPE_ASSURE || $search['tool_id'] == CustomerModel::SEARCH_TYPE_REVIEWED){
            //担保（产品：现金贷、分期、次月）
            $sql .= " LEFT JOIN consume_history h ON c.id = h.customer_id ";
            $sql .= $where;
            $sql .= " AND h.type IN ( ".$search['product_id']." ) ";
            if($county_id_str){
                $sql .= "AND h.county_id IN (".$county_id_str.")";
            }
            $sql .= " GROUP BY customer_id ORDER BY h.id DESC LIMIT 5";
        }else{
            //其他情况，获取全部联系人
            $sql .= $where;
            $sql .= ' ORDER BY id DESC LIMIT 10';
        }
        Log::write("sql=".$sql, Log::DEBUG);
        return $this->query($sql);
    }

    public function addClientUuid($device_id, $clinetidStr,$id,$mobile)
    {
        $sql = 'insert ignore  into client_uuid (uuid, client_id, add_time,customer_id,mobile) values ("'.$device_id.'", '.$clinetidStr.', "'.time().'","'.$id.'","'.$mobile.'")';
        Log::write($sql, Log::DEBUG);
        $info = M()->execute($sql);//下载激活记录表入库
        return true;
    }

    /*
     * 获得客户借款协议信息
     */
    public function getUserData($customerId,$where){
        $sql = 'SELECT
                    a.*,b.*
                FROM
                    customer a
                LEFT JOIN consume_history b ON a.id = b.customer_id
                WHERE
                a.id = '.$customerId.' AND b.type = 5  AND b.status = 1';
    
        $res = $this->query($sql);
        return $res;
    
    
    }
    /**********融360|根据用户名|返回md5签名|*********/
    public  function  checkRongUser($username){
        //用户查询
        $users=M('Customer')->field('id,mobile,id_num,pay_pass,add_time,real_name,type,api_userid,sesame_score')->where(['real_name'=>$username])->select();
        $return_mul=[];
            //重名用户
            foreach($users as $k=>$v){
                //$return_mul[]=strtoupper(trim(md5($v['mobile']).strtoupper(trim($v['id_num'])))).PHP_EOL;
                $return_mul[strtoupper(trim(md5($v['mobile']).strtoupper(trim($v['id_num']))))]=$v;

            }
        return  $return_mul;

    }
    /**********融360|*********/
    /**
     * 修改用户芝麻分认证
     * @param $customerId
     * @return bool
     */
    public function saveCustomerzhima($customerId)
    {
        $data['sesame_score'] = 0;
        $res = M('Customer')->where(['id'=>$customerId])->save($data);

        return $res;
    }
}
